package com.mezizy.ifaner;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.hjy.cache.AsyncImageLoader;
import com.hjy.cache.ImageCacheManager;
import com.mezizy.ifaner.global.Global;
import com.mezizy.ifaner.global.com.mezizy.ifaner.web.data.Dish;
import com.mezizy.ifaner.global.com.mezizy.ifaner.web.data.StoreInf;

import java.io.Serializable;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;


public class StoreActivity extends ActionBarActivity {
    ListView listDish;
    DishAdapter dishAdapter;
    TextView txtTotal, txtStoreName;

    StoreInf storeInf;

    String totalPrice = "0.00";
    String merchantId = "";
    String storeName = "";

    Map<String, Dish> cart = new HashMap<>();
    Map<String, Dish> dishArrayList = new HashMap<>();

    AsyncImageLoader imageLoader;

    @Override
    protected void onStart() {
        super.onStart();

        Global.activityLogInCheck(this);

        new zAsyncTask().execute();

    }
    @Override
    protected void onStop() {
        super.onStop();
        Global.dismissProgress(this);
    }

    public void imgNotifyDataSetChangedClick(View view) {
        dishAdapter.notifyDataSetChanged();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_store);
        getSupportActionBar().hide();

//          TODO
        merchantId = getIntent().getStringExtra("merchantId") == null ? "m001" : getIntent().getStringExtra("merchantId");
        storeName = getIntent().getStringExtra("storeName");

        listDish = ((ListView) findViewById(R.id.listDishes));

        txtTotal = (TextView) findViewById(R.id.txtTotalPrice);
        txtTotal.setText("NT " + "0.00");

        txtStoreName = ((TextView) findViewById(R.id.txtStoreName));
        txtStoreName.setText(storeName);

        ImageCacheManager cacheMgr = new ImageCacheManager(this);
        imageLoader = new AsyncImageLoader(this, cacheMgr.getMemoryCache(), cacheMgr.getPlacardFileCache());

        cart = new HashMap<>();
//        dishAdapter = new DishAdapter(this, getData(), R.layout.list_dish, new String[]{"img", "dishName", "inf", "monthSale", "price"}, new int[]{R.id.imgDish, R.id.txtDishName, R.id.txtDishInf, R.id.txtMonthSale, R.id.txtDishPrice});

//        listDish.setAdapter(dishAdapter);

        new zAsyncTask().execute();


    }

    /*
        button ；确认订单
     */
    public void btnConfirmOrderClick(View view) {
        if (cart.size() == 0) {
            Global.showToast("您还没有选择食物");
            return;
        }

        java.io.Serializable serializable = ((Serializable) cart);
        Intent intent = new Intent(StoreActivity.this, ConfirmActivity.class);
        intent.putExtra("cart", serializable);
        intent.putExtra("totalPrice", this.totalPrice);
        intent.putExtra("merchantId", this.merchantId);

        startActivity(intent);
    }


    public String getCartPrice() {
        float total = 0;
        for (Iterator iterator = cart.entrySet().iterator(); iterator.hasNext(); ) {
            Map.Entry map = (Map.Entry) iterator.next();
            String dishId = (String) map.getKey();
            Dish dish = (Dish) map.getValue();
            Integer quantity = dish.getCartQuantity();
            float price = dish.getDishesPrice();

            total += price * quantity;
        }
        DecimalFormat df = new DecimalFormat("#.00");
        this.totalPrice = df.format(total);

        return this.totalPrice;
    }

    public class DishAdapter extends SimpleAdapter {

        /**
         * Constructor
         *
         * @param context  The context where the View associated with this SimpleAdapter is running
         * @param data     A List of Maps. Each entry in the List corresponds to one row in the list. The
         *                 Maps contain the data for each row, and should include all the entries specified in
         *                 "from"
         * @param resource Resource identifier of a view layout that defines the views for this list
         *                 item. The layout file should include at least those named views defined in "to"
         * @param from     A list of column names that will be added to the Map associated with each
         *                 item.
         * @param to       The views that should display column in the "from" parameter. These should all be
         *                 TextViews. The first N views in this list are given the values of the first N columns
         */
        public DishAdapter(Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to) {
            super(context, data, resource, from, to);
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            final View view = super.getView(position, convertView, parent);

            final Map<String, Object> map = (Map<String, Object>) getItem(position);
            final String dishId = (String) map.get("dishId");
            final String merchantId = (String) map.get("merchantId");
//            final float dishPrice = Float.valueOf((String) map.get("price"));
            final float dishPrice = dishArrayList.get(dishId).getDishesPrice();

            //TODO
            final String cartQuantity = (cart.get(dishId) == null || cart.get(dishId).getCartQuantity() == 0) ?
                    "" : (String.valueOf(cart.get(dishId).getCartQuantity()) + " 份");
            ((TextView) view.findViewById(R.id.txtCartQuantity)).setText(cartQuantity);


            ImageView btnAddDish = ((ImageView) view.findViewById(R.id.btnDishAdd));


            btnAddDish.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //TODO 加入购物车


                    if (cart.get(dishId) == null) {
//                        cart.put(dishId, new Dish(dishId, merchantId, dishPrice));
                        cart.put(dishId, dishArrayList.get(dishId));

                        cart.get(dishId).setCartQuantity(1);


                    } else {
//                        cart.put(dishId, cart.get(dishId) + 1);
                        cart.get(dishId).setCartQuantity();
                    }
                    map.put("" + dishId, cart.get(dishId));
//                    Global.showToast(""+cart.get(dishId));
//                    Global.showToast(map.get( get) +"");

                    dishAdapter.notifyDataSetChanged();
                    txtTotal.setText("NT " + getCartPrice());
                }
            });

            ImageView btnRemoveDish = (ImageView) view.findViewById(R.id.cartRemove);
            if (cartQuantity.equals("")) {
                if (cart.get(dishId) != null) {
                    cart.remove(dishId);
                }
                btnRemoveDish.setVisibility(View.INVISIBLE);
            } else {
                btnRemoveDish.setVisibility(View.VISIBLE);

            }
            btnRemoveDish.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (cart.get(dishId) != null && cart.get(dishId).getCartQuantity() > 0) {
                        cart.get(dishId).setCartQuantity(cart.get(dishId).getCartQuantity() - 1);

                        notifyDataSetChanged();

                    }
                    txtTotal.setText("NT " + getCartPrice());

                }
            });

            ( findViewById(R.id.cardViewConfirm)).setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    switch (event.getAction()) {
                        case MotionEvent.ACTION_DOWN:
                            ((CardView) v).setCardBackgroundColor(getResources().getColor(R.color.main_orange_darker));

                            break;

                        case MotionEvent.ACTION_CANCEL:
                        case MotionEvent.ACTION_UP:
                            ((CardView) v).setCardBackgroundColor(getResources().getColor(R.color.main_orange));
                            break;
                    }
                    return  false;
                }
            });


            ImageView imgDish = ((ImageView) view.findViewById(R.id.imgDish));
            String imgUrl = (String) map.get("imgUrl");
//            imgUrl = "http://www.uisheji.com/wp-content/uploads/2011/11/07/1_111101085050_4.jpg";

            Bitmap bmp = null;
            if ((imgUrl == null || imgUrl.equals("null")) || imgUrl.equals("")) {
                imgDish.setImageResource(R.drawable.store_test_icon);
            } else {
                bmp = imageLoader.loadBitmap(listDish, imgUrl, true);
                if (bmp == null) {
                    imgDish.setImageResource(R.drawable.store_test_icon);
                } else {
                    imgDish.setImageBitmap(bmp);
                }
            }

            return view;
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_store, menu);
        return true;
    }

//    public List<Map<String, Object>> getData() {
//        List list = new ArrayList<Map<String, String>>();
//
//
//        return list;
//
//    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    public void btnStoreRefresh(View view) {
        new zAsyncTask().execute();
    }

    public class zAsyncTask extends AsyncTask<Object, List<Dish>, List<Dish>> {

        @Override
        protected List<Dish> doInBackground(Object[] params) {
            Global.showProgress(StoreActivity.this, "正在加载");
            storeInf = Global.getStoreInf(merchantId);

            List<Dish> dishes = null;
            try {
                //TODO

                if (merchantId == null) {
                    dishes = Global.getDishesList("m001");

                } else {
                    dishes = Global.getDishesList(merchantId);
                }
            } catch (Exception e) {
                e.printStackTrace();
                Global.dismissProgress(StoreActivity.this);
            }


            return dishes;
        }


        @Override
        protected void onPostExecute(List<Dish> dishes) {
            super.onPostExecute(dishes);

            List list = new ArrayList<Map<String, String>>();
            if (dishes == null) return;

            for (Iterator iterator = dishes.iterator(); iterator.hasNext(); ) {
                final Dish dish = (Dish) iterator.next();

                final Map map = new HashMap<>();

                map.put("dishId", dish.getDishesId());
                map.put("merchantId", dish.getMerchantId());
//                map.put("img", R.drawable.dish_test);
                map.put("imgUrl", dish.getDishesIconUrl());
//                map.put("monthSale", dish.getDishMonthSale());


                map.put("dishName", dish.getDishesName());
                map.put("monthSale", "月銷" + dish.getDishMonthSale());
                map.put("inf", "");
                map.put("price", "NT " + dish.getDishesPrice());

                list.add(map);

                dishArrayList.put(dish.getDishesId(), dish);
            }

//            dishAdapter = new DishAdapter(StoreActivity.this, list, R.layout.list_dish, new String[]{"img", "dishName", "monthSale", "inf", "price"}, new int[]{R.id.imgDish, R.id.txtDishName, R.id.txtMonthSale, R.id.txtDishInf, R.id.txtDishPrice});
            dishAdapter = new DishAdapter(StoreActivity.this, list, R.layout.list_dish, new String[]{"dishName", "monthSale", "inf", "price"}, new int[]{R.id.txtDishName, R.id.txtMonthSale, R.id.txtDishInf, R.id.txtDishPrice});
            dishAdapter.setViewBinder(new SimpleAdapter.ViewBinder() {
                @Override
                public boolean setViewValue(View view, Object data, String textRepresentation) {
                    return false;
                }
            });
            listDish.setAdapter(dishAdapter);

            ((TextView) findViewById(R.id.txtMonthSale)).setText("30天成交:\n" + storeInf.getMerchantMonthSale() + "(單)");
            ((TextView) findViewById(R.id.txtAvgHandleTime)).setText("平均接單時間：\n" + storeInf.getMerchantAvgHandleTime() + "(分)");
            ((TextView) findViewById(R.id.txtProcessNum)).setText("排隊人數\n" + storeInf.getMerchantProcessNum() + "(人)");


            Global.dismissProgress(StoreActivity.this);
        }
    }

    @Override
    public void onBackPressed() {
        startActivity(new Intent(StoreActivity.this, MainActivity.class));

        //super.onBackPressed();
    }
}
